﻿namespace zijian666.Updater;


public class UpdateManager : UpdateManager<LocalData, RemoteData>
{

}

public class UpdateManager<TLocalData, TRemoteData>
    where TLocalData : LocalData, new()
    where TRemoteData : RemoteData, new()
{
    public TLocalData LocalData { get; protected set; } = new();
    public TRemoteData RemoteData { get; protected set; } = new();

    /// <summary>
    /// 加载本地配置文件
    /// </summary>
    /// <returns></returns>
    /// <exception cref="FileNotFoundException"> 未找到本地配置文件 </exception>
    public ValueTask LoadLocal()
    {
        (string, Func<string, ValueTask>)[] loaders = [
           (Updater.LocalData.AppName + ".jsonc", LocalData.LoadFromJson),
           (Updater.LocalData.AppName + ".json", LocalData.LoadFromJson),
        ];
        try
        {
            foreach (var (file, func) in loaders)
            {
                var path = Path.Combine(Updater.LocalData.CD, file);
                if (File.Exists(path))
                {
                    return func(path);
                }
            }
        }
        catch (Exception e)
        {
            throw new InvalidOperationException("加载本地配置文件失败", e);
        }
        throw new FileNotFoundException("未找到本地配置文件");
    }

    /// <summary>
    /// 加载远程配置文件
    /// </summary>
    /// <returns></returns>
    /// <exception cref="ArgumentNullException"> 未加载本地配置或本地配置中未设置 <see cref="LocalData.VersionMetadataUrl"/> </exception>
    public ValueTask LoadRemote()
    {
        var url = LocalData.VersionMetadataUrl;
        if (string.IsNullOrWhiteSpace(url))
        {
            throw new ArgumentNullException($"未加载本地配置或本地配置中未设置 {nameof(LocalData.VersionMetadataUrl)}");
        }
        try
        {
            return RemoteData.LoadFromJson(url);
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException("加载远程配置文件失败", ex);
        }
    }

    /// <summary>
    /// 检查是否有新版本
    /// </summary>
    /// <returns></returns>
    /// <exception cref="ArgumentNullException"></exception>
    public bool HasNewVersion()
    {
        if (LocalData.Version is null)
        {
            throw new ArgumentNullException($"未加载本地配置或本地配置中未设置 {nameof(LocalData.Version)}");
        }
        if (RemoteData.LoadTime is null)
        {
            throw new ArgumentNullException("未加载远程配置");
        }
        var latestVersion = RemoteData[0];
        return latestVersion.Version > LocalData.Version;
    }
}
